package cn.dliyy.warehouse.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

//@Repository
public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao {
	@Override
	public List<Object> createQuery(final String queryString) {
		return (List<Object>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
			public Object doInHibernate(org.hibernate.Session session) {
				Query query = session.createQuery(queryString);
				List<Object> rows = query.list();
				return rows;
			}
		});
	}

	@Override
	public List<Object> createQuery(final String queryString, final int start, final int length) {
		return (List<Object>) getHibernateTemplate().execute(new HibernateCallback<Object>() {
			public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException {
				Query query = session.createQuery(queryString);
				query.setFirstResult(start);
				query.setMaxResults(length);
				List<Object> rows = query.list();
				return rows;
			}
		});
	}

	@Override
	public Object save(final Object model) {
		return getHibernateTemplate().execute(new HibernateCallback<Object>() {
			public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException {
				session.save(model);
				return null;
			}
		});
	}

	@Override
	public void update(final Object model) {
		getHibernateTemplate().execute(new HibernateCallback<Object>() {
			public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException {
				session.update(model);
				return null;
			}
		});
	}

	@Override
	public void delete(final Object model) {
		getHibernateTemplate().execute(new HibernateCallback<Object>() {
			public Object doInHibernate(org.hibernate.Session session) throws org.hibernate.HibernateException {
				session.delete(model);
				return null;
			}
		});
	}

	@Override
	public Object get(final Class<?> clazz, final Serializable id) {
		if (id == null) {
			return null;
		}
		return get(clazz, id.toString());
		// return getHibernateTemplate().get(clazz,id);
	}

	@Override
	public Object get(final Class<?> clazz, final String primaryKey) {
		if (primaryKey == null) {
			return null;
		}
		StringBuffer sff = new StringBuffer();
		sff.append("from ").append(clazz.getSimpleName()).append(" a where a.id='").append(primaryKey + "'");
		List<Object> list = createQuery(sff.toString());
		if (list == null || list.size() != 1) {
			return null;
		}
		return list.get(0);
	}

	@Override
	public Object get(Class<?> clazz, Object o) {
		/* 主键或者复合主键查询，未实现。 */
		return null;
	}

}